# FeedManager - Manage feeds
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"

import os
from pysqlite2 import dbapi2 as sqlite
from backend.components.feeds.feed_fetcher import FeedFetcher

# Messaging system
from backend.core.message import Message
from backend.core.message_type_priority import MessageType
from backend.core.message_bus import MessageBus
from backend.core.message_handler import MessageHandler

class FeedManager(MessageHandler):
    """Backend feed manager keeps feeds cache database updated."""

    # Feed cache database file
    FEED_DB = os.path.expanduser('~/.entertainer/cache/feed.db')

    def __init__(self, message_bus, logger, configuration):
        """
        Create a new FeedManager object
        @param message_bus: MessageBus object
        @param logger: Logger object
        @param configuration: Configuration object
        """
        self.message_bus = message_bus
        self.logger = logger
        self.configuration = configuration
        if not os.path.exists(self.FEED_DB):
            self.createFeedCacheDatabase()
      
    def updateFeedCache(self):
        """
        Update all feeds to cache in a new thread and after 
        that emit FEED_DB_UPDATED message to the messagebus.
        """
        fetch_thread = FeedFetcher(self.message_bus, 
                                   self.logger, 
                                   self.configuration.get_feeds())
        fetch_thread.start()
    
    def createFeedCacheDatabase(self):
        """Create a feed cache database file and tables."""
        db_conn = sqlite.connect(self.FEED_DB)
        db_cursor = db_conn.cursor()
        db_cursor.execute("""CREATE TABLE feed(
                                url TEXT, 
                                title TEXT, 
                                subtitle TEXT, 
                                description TEXT, 
                                time TIME,
                                date DATE,
                                PRIMARY KEY(url))""")
                                
        db_cursor.execute("""CREATE TABLE entry(
                                feed_url TEXT,
                                title TEXT,
                                description TEXT,
                                isread TEXT,
                                time TIME,
                                date DATE,
                                id TEXT,
                                PRIMARY KEY(id))""")
        db_conn.commit()
        db_conn.close()
        
    def wipeFeedCacheDatabase(self):
        """Wipes the feed cache database file and tables."""
        # all we need to do to wipe the cache database is to drop the two tables containing the data: feed and entry
        db_conn = sqlite.connect(self.FEED_DB)
        db_cursor = db_conn.cursor()
        db_cursor.execute("""DROP TABLE feed IF EXISTS""")
        db_cursor.execute("""DROP TABLE entry IF EXISTS""")
        db_conn.commit()
        db_conn.close()
                
    # Implementes MessageHandler interface
    def handleMessage(self, message):
        """
        Handle the received message
        @param message: Received Message object
        """
        if message.get_type() == MessageType.UPDATE_FEEDS:
            self.updateFeedCache()
        elif message.get_type() == MessageType.REBUILD_FEED_CACHE:
            #rebuild feed cache
            self.rebuildFeedCacheDatabase()
            
    def rebuildFeedCacheDatabase(self):
        """Destroy all current data and index everything from the scratch."""
        self.logger.info("Feed cache rebuilding requested")
        #we remove the tables from the database the create them again, this wipes the tables
        self.wipeFeedCacheDatabase()
        self.createFeedCacheDatabase()
        #there will be no data in the tables so we need to populate the feed cache
        self.updateFeedCache()
        self.logger.info("Feed cache rebuilt")
        
            
    def getName(self):
        """Get MessageHandler name."""
        return "FeedManager"
